package com.xw.cor.servelt;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: xw
 * @create: 2022/10/18 13:55
 * @description:
 */
public class ServletV2 {

    public static void main(String[] args) {
        Request request = new Request();
        request.str = "大家好:)，<script>，欢迎访问 mashibing.com ，大家都是996 ";
        Response response = new Response();
        response.str = "response";

        FilterChain chain = new FilterChain();
        chain.add(new HTMLFilter()).add(new SensitiveFilter());
        chain.doFilter(request, response, chain);
        System.out.println(request.str);
        System.out.println(response.str);

    }

    static class Request {
        String str;
    }

    static class Response {
        String str;
    }

    interface Filter {
        boolean doFilter(Request request, Response response, FilterChain chain);
    }

    static class HTMLFilter implements Filter {
        @Override
        public boolean doFilter(Request request, Response response, FilterChain chain) {
            request.str = request.str.replaceAll("<", "[").replaceAll(">", "]");
            chain.doFilter(request,response,chain);
            response.str = response.str + "HTMLFilter";
            return true;
        }
    }

    static class SensitiveFilter implements Filter {

        @Override
        public boolean doFilter(Request request, Response response, FilterChain chain) {
            request.str = request.str.replaceAll("996", "955");
            chain.doFilter(request,response,chain);
            response.str = response.str + "SensitiveFilter";
            return true;
        }
    }

    static class FilterChain implements  Filter{
        int index = 0;

        List<Filter> filters = new ArrayList<>();

        public FilterChain add(Filter f){
            filters.add(f);
            return this;
        }

        @Override
        public boolean doFilter(Request request, Response response, FilterChain chain) {
            if(index == filters.size()){
                return false;
            }
            Filter f = filters.get(index);
            index ++;

            return f.doFilter(request, response, chain);
        }
    }

}
